package com.tian.print.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.postek.coyote.postekwifi.MainActivity;
import com.tian.print.HomeActivity;
import com.tian.print.R;
import com.tian.print.app.RepositoryManagerApp;
import com.tian.print.bean.UserInfo;
import com.tian.print.http.LoadingDialog;
import com.tian.print.http.error.ApiException;
import com.tian.print.login.contract.ILoginContract;
import com.tian.print.login.presenter.LoginPresenter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity implements ILoginContract.ILoginView {

    @BindView(R.id.et_name)
    EditText et_name;

    @BindView(R.id.et_pwd)
    EditText et_pwd;

    @BindView(R.id.btn_login)
    Button btn_login;

    private LoginPresenter mLoginPresenter;

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        mLoginPresenter = new LoginPresenter(this);
        getLifecycle().addObserver(mLoginPresenter);
        loadingDialog = LoadingDialog.newInstance(null);
    }

    @OnClick(R.id.btn_login)
    public void onClick(View v) {
        if (!verityInput())
            return;
        loadingDialog.show(this);
        mLoginPresenter.login(et_name.getText().toString(), et_pwd.getText().toString());
    }

    private boolean verityInput() {
        if (et_name.getText().toString() == null || TextUtils.isEmpty(et_name.getText().toString())) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_LONG).show();
            return false;
        }
        if (et_pwd.getText().toString() == null || TextUtils.isEmpty(et_pwd.getText().toString())) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    public void onLoginSuceess(UserInfo userInfo) {
        loadingDialog.dismiss();

        RepositoryManagerApp.setUserInfo(userInfo);
        Log.i("net", userInfo.toString());
        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    }

    @Override
    public void onLoginError(ApiException e) {
        loadingDialog.dismiss();
        Toast.makeText(this, e.getErrorMsg(), Toast.LENGTH_LONG).show();
        Log.i("loginError", e.getErrorMsg());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        loadingDialog.dismiss();
    }
}
